/* eslint-disable import/no-dynamic-require */
/* eslint-disable import/no-extraneous-dependencies */
const { execSync } = require('child_process'); // 同步子进程
const fs = require('fs');
const chalk = require('chalk');
const { join } = require('path');

const version = process.env.npm_package_version;
const releaseV = process.env.npm_package_releaseVersion;

const refs = fs
  .readFileSync(join(__dirname, '..', '.git', 'HEAD'))
  .toString('utf-8')
  .trim()
  .replace(/^ref: ?/i, '');

const commitMsg = execSync('git show -s --format=%s')
  .toString()
  .trim();

console.log(chalk.bold.green('当前版本号:'), chalk.bold.blueBright(version));
console.log(chalk.bold.green('上次版本号:'), chalk.bold.yellowBright(releaseV));
console.log(chalk.bold.green('当前分支:'), chalk.bold.green(refs));
console.log(
  chalk.bold.green('commit信息:'),
  chalk.bold.green(`"${commitMsg}"`),
);

const isMaster = refs === 'refs/heads/master';
const isRelease = /^release: (.*)/g.test(commitMsg);
const isChangeNo = version !== releaseV;

if (!isMaster) {
  throw new Error(chalk.bold.red('请在master分支发release'));
} else if (!isRelease) {
  throw new Error(chalk.bold.red('commit type需为release'));
} else if (!isChangeNo) {
  throw new Error(chalk.bold.red('请修改版本号'));
}
